package com.example.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;

/**
 * 存取List工具类
 * SharedPreferencesListUtils
 *
 * @author wulu
 * @version [V0.0.1, 2020/1/2]
 * @since V0.0.1
 */

class SPListUtils {
    private static final String TAG = "SPListUtils";

    private static Context context;

    private static SharedPreferences sharedPreferences;

    /**
     * 构造方法传递一个上下文
     * @param context context
     */
    public SPListUtils(Context context) {
        this.context = context;
    }

    /**
     * 保存频道列表
     * @param list list
     * @param <T>  T
     *
     */
    public static <T> void saveChannleData(List<T> list) {
        if ((list != null) && (list.size() > 0)) {
            Log.i(TAG, "savedata:");
            sharedPreferences = context.getSharedPreferences("SP_ChannleData_List", context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            String jsonStr = JSON.toJSONString(list);
            editor.putString("KEY_ChannleData_LIST_DATA", jsonStr);
            editor.commit();
        } else {
            Log.e(TAG, "savedata: 保存失败 ");
        }
    }

    /**
     * 获取频道列表
     * @param <T> T
     * @return list
     *
     */

    public static <T> List<T> getChannleData() {
        // 创建sp对象,如果有key为"SP_PEOPLE"的sp就取出
        SharedPreferences sp = context.getSharedPreferences("SP_ChannleData_List", context.MODE_PRIVATE);
        // 取出key为"KEY_PEOPLE_DATA"的值，如果值为空，则将第二个参数作为默认值赋值
        String peopleListJson = sp.getString("KEY_ChannleData_LIST_DATA", "");
        Log.i(TAG, "getChannleData: peopleListJson"+peopleListJson);
        List<T> channelItems = new ArrayList<>();
        if (peopleListJson==null&&peopleListJson.length()==0) {
            channelItems = null;
            Log.e(TAG, "getChannleData: 频道为空");
        } else {
            try {
                channelItems = (ArrayList<T>) JSON.parseObject(peopleListJson, List.class);
                Log.i(TAG, "getChannleData: "+channelItems);
            } catch (Exception e) {
                e.fillInStackTrace();
            } finally {
            }
        }
        return channelItems;
    }
}
